package com.beiing.tianshuai.tianshuai.mine.ui;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.CommonBean;
import com.beiing.tianshuai.tianshuai.network.DataManager;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.RegexUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;

public class SignUpEnterTelActivity extends BaseActivity {

    @BindView(R.id.toolbar_iv_back)
    ImageView mToolbarIvBack;
    @BindView(R.id.toolbar_tv_title)
    TextView mToolbarTvTitle;
    @BindView(R.id.et_phone_number)
    EditText mEtPhoneNumber;
    @BindView(R.id.btn_get_safe_code)
    TextView mBtnGetSafeCode;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sign_up_enter_tel;
    }

    @Override
    protected void init() {
        ButterKnife.bind(this);
        initToolbar();
        initListener();
    }

    private void initToolbar() {
        mToolbarIvBack.setVisibility(View.VISIBLE);
        mToolbarTvTitle.setText("手机号注册");
    }

    private void initListener() {
        // 手机号码输入框检测，当满足手机号码规则的时候设置btnEnabled为true，否则设置为false
        mEtPhoneNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String mobile = s.toString();
                if (RegexUtils.checkMobile(mobile)) {
                    mBtnGetSafeCode.setEnabled(true);
                } else {
                    mBtnGetSafeCode.setEnabled(false);
                }
            }
        });

        // 获取验证码
        mBtnGetSafeCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mBtnGetSafeCode.setEnabled(false);
                isAlreadySignUp(mEtPhoneNumber.getText().toString());
            }
        });

        // 返回
        mToolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    /**
     * 判断当前用户是否注册
     * code = 200 已注册
     * code = 400 未注册
     *
     * @param phoneNum 手机号码
     */
    private void isAlreadySignUp(final String phoneNum) {
        DisposableObserver<CommonBean> observer = new DisposableObserver<CommonBean>() {
            @Override
            public void onNext(@NonNull CommonBean bean) {
                int code = bean.getCode();
                mBtnGetSafeCode.setEnabled(true);
                switch (code) {
                    case 200:
                        showShortText("该账号已注册");
                        break;
                    case 400:
                        getSafeCode(phoneNum);
                        break;
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                showShortText("请求失败");
                mBtnGetSafeCode.setEnabled(true);
                LogUtils.e(e.getMessage(), "error");
            }

            @Override
            public void onComplete() {

            }
        };
        DataManager.isAlreadySignUp(phoneNum)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    /**
     * 如果获取验证码成功，则跳转到下一个界面。
     *
     * @param phoneNum 用户的手机号码
     */
    private void getSafeCode(final String phoneNum) {
        DisposableObserver<CommonBean> observer = new DisposableObserver<CommonBean>() {
            @Override
            public void onNext(@NonNull CommonBean bean) {
                int code = bean.getCode();
                switch (code) {
                    case 200:
                        String safeCode = bean.getData().getNumber();
                        LogUtils.i("验证码：" + safeCode, "SafeCode");
                        Intent intent = new Intent(mContext, SignUpEnterSafeCodeActivity.class);
                        intent.putExtra("phoneNum", phoneNum);
                        intent.putExtra("safeCode", safeCode);
                        startActivity(intent);
                        break;
                    case 401:
                        showShortText("获取验证码失败");
                        break;
                    case 400:
                        showShortText("手机号格式不正确");
                        break;
                    default:
                        showShortText("获取验证码失败");
                        break;
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        };
        DataManager.getSafeCodeResult(phoneNum)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
}
